package com.yaoandw.givebook;

import org.apache.log4j.Logger;

import com.yaoandw.storage.FrontierFactory;
import com.yaoandw.storage.SimpleCrawlUrl;

public class DispatcherThread implements Runnable {
	private static Logger logger = Logger.getLogger(DispatcherThread.class);
	private BookCrawler crawler;
	public DispatcherThread(BookCrawler crawler){
		this.crawler = crawler;
	}
	private boolean crawler_waited = false;
	public void run() {
		logger.debug("DispatcherThread start..");
		while(true){
			if(Constants.status_running.equals(Constants.status)){
//				if(crawler_waited){
//					synchronized (crawler) {
//						crawler.notify();
//						crawler_waited = false;
//					}
//				}
				int activePoolCount = crawler.getActivePoolCount();
				if(activePoolCount < crawler.getMaxPoolSize()){
					SimpleCrawlUrl nextUrl = FrontierFactory.getFrontier(null).getNext();
					if(nextUrl == null)
						continue;
					logger.debug("Dispatchering url:"+nextUrl.getOriUrl());
					crawler.assign(nextUrl);
				}else{
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						logger.error("",e);
					}
				}
				if(activePoolCount <=0 && crawler.poolIsShutdown()){
					break;
				}
			}else if(Constants.status_paused.equals(Constants.status)){
				synchronized (this) {
					try {
						wait();
					} catch (InterruptedException e) {
						logger.error("",e);
					}
				}
//				synchronized (crawler) {
//					try {
//						crawler.wait();
//						crawler_waited = true;
//					} catch (InterruptedException e) {
//						logger.error("",e);
//					}
//				}
			}else if(Constants.status_stoped.equals(Constants.status)){
				break;
			}
			
		}
		logger.debug("DispatcherThread stop..");
	}

	
}
